package indi.h.devmg.acquisition.snmp.mib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import indi.h.devmg.acquisition.snmp.mib.beans.MIB;
import indi.h.devmg.acquisition.snmp.mib.handles.MIBHandle;
import indi.h.devmg.acquisition.snmp.mib.rules.MIBRule;

public class MIBAnalyst {
	/**
	 * mib库文件解析
	 * 
	 * @param files
	 * @return
	 */
	public static MIB analysisMIB(File[] files) {
		MIB[] m = new MIB[files.length];
		int i = 0;
		for (File f : files) {
			m[i] = createMIB(f);
			i++;
		}
		MIB all = new MIB();
		for (MIB mm : m) {
			all.getNodes().putAll(mm.getNodes());
		}
		analysisOid(all);
		return all;
	}

	/**
	 * mib文件解析
	 * 
	 * @param file
	 * @return
	 */
	public static MIB analysisMIB(File file) {
		MIB createMIB = createMIB(file);
		analysisOid(createMIB);
		return createMIB;
	}

	/**
	 * 解析生成MIB对象
	 * 
	 * @param file
	 * @return
	 */
	protected static MIB createMIB(File file) {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
			String line = br.readLine();
			MIBRule mr = new MIBRule();
			while (line != null) {
				mr.addData(line);
				line = br.readLine();
			}
			MIB target = mr.getTarget();
			return target;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 分析MIB的Node得出oid
	 * 
	 * @param mib
	 */
	protected static void analysisOid(MIB mib) {
		MIBHandle mh = new MIBHandle();
		mh.handle(mib);
	}
}
